/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.edu.agh.administracja.networkconfig.model.util;

import java.util.List;
import pl.edu.agh.administracja.networkconfig.model.NetworkInterfaceConfig;

/**
 *
 * @author radek
 */
public class ConfigIO {
    
    private ConfigIO() {        
    }
   
    public static void saveConfiguration(List<NetworkInterfaceConfig> interfaces) {
        StringBuilder sb = new StringBuilder();

        // loopback
        sb.append("auto lo\niface lo inet loopback\n\n");

        for (NetworkInterfaceConfig nic : interfaces) {
            sb.append(ConfigIO.configValueOf(nic));
        }
        
        ShellExecutor.executeSynchronouslyAsRoot("echo \"" + sb.toString() + "\" > /etc/network/interfaces");
    }
    
    public static String configValueOf( NetworkInterfaceConfig nic) {
        StringBuilder sb = new StringBuilder();
        sb.append("auto ").append(nic.getName()).append("\n");
        sb.append("iface ").append(nic.getName()).append(" inet");
        
        if(nic.isIpViaDHCP()) {
            sb.append(" dhcp\n");
        }else {
            sb.append(" static\n");
            
            if(nic.getIpAddress() != null)
                sb.append("\taddress ").append(nic.getIpAddress().toString()).append("\n");
            
            if(nic.getMask() != null)
                sb.append("\tnetmask ").append(nic.getMask().toString()).append("\n");
            
            if(nic.getDefaultGateway() != null)
                sb.append("\tgateway ").append(nic.getDefaultGateway().toString()).append("\n");
            
            if(nic.getHardwareAddress() != null)
                sb.append("\thwaddress ").append(nic.getHardwareAddress().toString()).append("\n");
        }
        
        sb.append("\n");
        
        return sb.toString();
    }
}
